package com.chaoxin.lovehelp.controller;

import java.text.ParseException;
import java.util.*;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chaoxin.lovehelp.common.validator.IdCardCheck;
import com.chaoxin.lovehelp.entity.FellowEntity;
import com.chaoxin.lovehelp.common.enums.SystemEnum;
import com.chaoxin.lovehelp.common.enums.vo.allRecipientVo;
import com.chaoxin.lovehelp.common.enums.vo.recipientSelectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import com.chaoxin.lovehelp.entity.RecipientEntity;
import com.chaoxin.lovehelp.service.RecipientService;
import com.chaoxin.lovehelp.common.utils.PageUtils;
import com.chaoxin.lovehelp.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author honghu
 * @email 3027708213@qq.com
 * @date 2024-02-04 22:13:14
 */
@RestController
@CrossOrigin
@RequestMapping("lovehelp/recipient")
public class RecipientController {
    @Autowired
    private RecipientService recipientService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,HttpServletRequest request){
        PageUtils page = recipientService.queryPage(params,request);
        return R.ok().put("page", page);
    }


    /**
     * 单个受助者信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
        allRecipientVo vo = recipientService.getRecipientVo(id);

        return R.ok().put("recipient", vo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody RecipientEntity recipient,HttpServletRequest request) throws ParseException {
        FellowEntity fellowEntity =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        if (fellowEntity.getRole()==1 || fellowEntity.getRole()==2){
            IdCardCheck cardCheck = new IdCardCheck();
            if(recipient.getTel()!=null){
                //电话号校验
                if(!cardCheck.checkTel(recipient.getTel())){
                    return R.error(400,"请输入正确的受助者电话号。");
                }
            }
            if(recipient.getTownTel()!=null){
                //电话号校验
                if(!cardCheck.checkTel(recipient.getTownTel())) {
                    return R.error(400,"请输入正确的镇干部电话号。");
                }
            }

            if(recipient.getVillageTel()!=null){
                //电话号校验
                if (!cardCheck.checkTel(recipient.getVillageTel())){
                    return R.error(400,"请输入正确的乡干部电话号。");
                }
            }

            if(recipient.getNurseTel()!=null){
                //电话号校验
                if(!cardCheck.checkTel(recipient.getNurseTel())){
                    return R.error(400,"请输入正确的护理人电话号。");
                }
            }
            if(recipient.getBirthDate()!=null){
                //根据生日计算年龄
                recipient.setAge(getAgeByBirth(recipient.getBirthDate()));
            }

            if(!StringUtils.isEmpty(recipient.getIdentityId())){
                QueryWrapper<RecipientEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("is_display",1).eq("identity_id",recipient.getIdentityId());
                List<RecipientEntity> list = recipientService.list(wrapper);
                if(!CollectionUtils.isEmpty(list)){

                    return R.error(300,"该受助者已存在。");
                }
                //身份证号校验
                if(cardCheck.checkIdCardNum(recipient.getIdentityId())){
                    recipient.setIsDisplay(1);
                    recipientService.save(recipient);

                    return R.ok();
                }else return R.error(400,"请输入正确的身份证号。");
            }
            recipient.setIsDisplay(1);
            recipientService.save(recipient);
            return R.ok();
        }
        return R.error("无权限添加，请联系管理员");

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody RecipientEntity recipient) throws ParseException {
        System.out.println(recipient);
        if(recipient.getFellowId()==null){
            recipient.setFellowId(null);
        }
        if(recipient.getBirthDate()!=null){
            recipient.setAge(getAgeByBirth(recipient.getBirthDate()));
        }
        IdCardCheck cardCheck = new IdCardCheck();
        if(recipient.getTel()!=null){
            if(!cardCheck.checkTel(recipient.getTel())){
                return R.error(400,"请输入正确的受助者电话号。");
            }
        }
        if(recipient.getTownTel()!=null){
            if(!cardCheck.checkTel(recipient.getTownTel())) {
                return R.error(400,"请输入正确的镇干部电话号。");
            }
        }

        if(recipient.getVillageTel()!=null){
            if (!cardCheck.checkTel(recipient.getVillageTel())){
                return R.error(400,"请输入正确的乡干部电话号。");
            }
        }

        if(recipient.getNurseTel()!=null){
            if(!cardCheck.checkTel(recipient.getNurseTel())){
                return R.error(400,"请输入正确的护理人电话号。");
            }
        }

        if(!StringUtils.isEmpty(recipient.getIdentityId())){

            if(!cardCheck.checkIdCardNum(recipient.getIdentityId()))
                return R.error(400,"请输入正确的身份证号。");
        }
        recipientService.updateById(recipient);

        return R.ok();

    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids, HttpServletRequest request){
        FellowEntity fellowEntity =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        if (fellowEntity.getRole()==1){
            recipientService.removeIds(Arrays.asList(ids));
            return R.ok();
        }
        return R.error("无法删除请联系超级管理员");

    }
    /**
     * 获取所有受助者信息，下拉框所有受助者
     */
    @RequestMapping("/allrecipient")
    public R getAllRecipient(HttpServletRequest request){
        List<recipientSelectVo> recipients = recipientService.getAllRecipient(request);
        return R.ok().put("recipients",recipients);

//        return R.error(401,"无法获取所有受助者信息");

    }
    private static int getAgeByBirth(Date birthday) {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
            return 0;
        }
    }

}
